package com.alibaba.datax.plugin.writer.doriswriter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Arrays;

public class HttpUtil {

    /**
     * 执行HTTP GET请求，并返回响应的前20行数据。
     *
     * @param urlString 请求的URL字符串
     * @return lineLimit 行数限制后的响应数据
     * @throws IOException 如果发生I/O错误
     */
    public static String getLogContent(String urlString) throws IOException {
        int lineLimit = 20;
        URL url = new URL(urlString);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String[] lines = new String[lineLimit];
            int lineCount = 0;
            String inputLine;

            while ((inputLine = in.readLine()) != null && lineCount < lineLimit) {
                lines[lineCount++] = inputLine;
            }
            String[] strings = Arrays.copyOf(lines, lineCount);
            //转换为字符串加上换行符
            return String.join("\n", strings);
        }catch (UnknownHostException e){
            return "ErrorURL 无法访问，请检查主机映射是否正确";
        }catch (Exception e){
            return  "Error 未知错误,请登录服务器查看日志";
        }
        finally {
            con.disconnect();
        }
    }

    public static void main(String[] args) throws IOException {

        String logContent = getLogContent("http://10.0.2.29:8041/api/_load_error_log?file=__shard_9/error_log_insert_stmt_f34b3d1e8a61b209-a9de5d62d3eba69d_f34b3d1e8a61b209_a9de5d62d3eba69d");
        System.out.println("First 20 lines of the log content:"+logContent);

    }
}